<?php


namespace App\Exports;

use App\Models\PartCompany;
use App\Models\ProjectClassify;
use App\Services\BaseService;
use App\Services\CommonService;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

/**
 * Class BookTitleExport29
 * @package App\Exports
 * 29号案卷目录导出格式
 */
class BookTitleExport8 implements  FromCollection, WithTitle, WithColumnWidths, WithStyles,  WithCustomStartCell
{
    use Exportable;

    protected  $totalRow; //总行数
    protected  $partCompanyId; //参见单位
    protected  $partCompanyName; //参见单位名字
    protected  $projectClassifyId; //项目分类
    protected  $projectClassifyName; //项目分类名称
    protected  $bookTitleIds; //指定的案卷

    public function __construct($bookTitleIds)
    {
        $this->partCompanyId       = request()->input('part_company_id', 0);
        $this->partCompanyName     = PartCompany::query()->where('id', $this->partCompanyId)->value('title');
        $this->projectClassifyId   = request()->input('project_classify_id', 0);
        $this->projectClassifyName = ProjectClassify::query()->where('id', $this->projectClassifyId)->value('title');
        $this->bookTitleIds        = $bookTitleIds;
    }

    /**
     * 获取数据集合
     * $partCompany = PartCompany::query()->where('id', $partCompanyId)->value('title') ?: '未知';
     * $projectClassify = ProjectClassify::query()->where('id', $projectClassifyId)->value('title') ?: '未知';
     */
    public function collection()
    {
        $bookTitleInstance = (new BaseService())->getBookTitleInstance($this->partCompanyId, $this->projectClassifyId);
        $bookTitleIds = $this->bookTitleIds;
        $list = $bookTitleInstance
            ->when($bookTitleIds, function ($query) use ($bookTitleIds) {
                return $query->whereIn('id', $bookTitleIds);
            })
            ->where('part_company_id', $this->partCompanyId)
            ->where('project_classify_id', $this->projectClassifyId)
            ->select('id', 'archives_no', 'title', 'blueprint', 'base_map', 'volume', 'page_num', 'years', 'store_period', 'secret_level', 'cabin_no', 'remark', 'mixed_no')
            ->orderBy('serial_no')
            ->get();

        if ($list->isEmpty()) return collect([]);

        $list = $list->toArray();
        $r_list = [];
        foreach ($list as $key=>$val) {
            $arr['number']        = $key + 1;              //序号
            $arr['archives_no']   = $val['archives_no'];   //档案号
            $arr['title']         = htmlspecialchars_decode($val['title']); //案卷题名
            $arr['blueprint']     = $val['blueprint'];     //蓝图
            $arr['base_map']      = $val['base_map'];      //底图
            $arr['volume']        = $val['volume'];        //册
            $arr['page_num']      = $val['page_num'];      //张
            $arr['years']         = $val['years'];         //年代
            $arr['store_period']  = $val['store_period'];  //保管期限
            $arr['secret_level']  = $val['secret_level'];  //保密程度
            $arr['cabin_no']      = $val['cabin_no'];      //柜号
            $arr['remark']        = $val['remark'];        //备注
            $arr['mixed_no']      = $val['mixed_no'];      //互见号
            $arr['part_company']  = $this->partCompanyName;//形成单位
            $arr['data_count']     = CommonService::getBookCatalogInstance($this->partCompanyId, $this->projectClassifyId)->where('book_title_id', $val['id'])->count() ?: 0;
            $r_list[] = $arr;
        }
        $this->totalRow = count($r_list) + 3;

        return collect($r_list);
    }

    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->projectClassifyName;
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 10, 'B' => 30, 'C' => 60, 'D'=>8, 'E'=>8, 'F'=>8, 'G'=>8, 'H'=>10, 'I'=>10, 'J'=>10, 'K'=>10, 'L'=>10, 'M'=>10, 'N'=>30, 'O'=>7
        ];
    }

    /**
     * 从哪个单元格开始渲染数据，数据集合如 $list
     * @return string
     */
    public function startCell(): string
    {
        return 'A4';
    }

    /**
     * 样式设置
     * @param Worksheet $sheet
     * @throws PhpSpreadsheetException
     */
    public function styles(Worksheet $sheet)
    {
        /**
         * 设置为 A4纸
         */
        $pageSetup = new PageSetup();
        $pageSetup->setPaperSize(9);
        $sheet->setPageSetup($pageSetup);
        /**
         * 设置页边距
         */
        $pageMargins = new PageMargins();
        $pageMargins->setTop(0.2);
        $pageMargins->setRight(0.3);
        $pageMargins->setLeft(0.5);
        $sheet->setPageMargins($pageMargins);

        $sheet->getDefaultRowDimension()->setRowHeight(42); //设置行高(全部行高)

        $sheet->getStyle('A1:G'.$this->totalRow)->getFont()->setName('宋体'); //宋体
        $sheet->getStyle('C4:G'.$this->totalRow)->getFont()->setSize(11); //大小

        $sheet->mergeCells('A1:O1');
        $sheet->setCellValue('A1', '科 技 档 案 案 卷 目 录');

        $sheet->mergeCells('A2:A3');
        $sheet->setCellValue('A2', '顺
号');

        $sheet->mergeCells('B2:B3');
        $sheet->setCellValue('B2', '档案号');

        $sheet->mergeCells('C2:C3');
        $sheet->setCellValue('C2', '名称');

        $sheet->mergeCells('D2:E2');
        $sheet->setCellValue('D2', '种类');
        $sheet->setCellValue('D3', '蓝图');
        $sheet->setCellValue('E3', '底图');

        $sheet->mergeCells('F2:G2');
        $sheet->setCellValue('F2', '数量');
        $sheet->setCellValue('F3', '册');
        $sheet->setCellValue('G3', '张');

        $sheet->mergeCells('H2:H3');
        $sheet->setCellValue('H2', '所属
年代');

        $sheet->mergeCells('I2:I3');
        $sheet->setCellValue('I2', '保管
期限');

        $sheet->mergeCells('J2:J3');
        $sheet->setCellValue('J2', '机密
程度');

        $sheet->mergeCells('K2:K3'); //柜号
        $sheet->setCellValue('K2', '柜号');

        $sheet->mergeCells('L2:L3');
        $sheet->setCellValue('L2', '备注');

        $sheet->mergeCells('M2:M3');
        $sheet->setCellValue('M2', '互见号');

        $sheet->mergeCells('N2:N3');
        $sheet->setCellValue('N2', '形成单位');

        $sheet->mergeCells('O2:O3');
        $sheet->setCellValue('O2', '卷内数量');

        /**
         * 顶部案卷目录样式设置
         */
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setVertical('center');//垂直居中
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setHorizontal('center');//水平居中
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setWrapText(true); //自动换行
        //案卷标题居左
        $sheet->getStyle('C4:C' . $this->totalRow)->getAlignment()->setHorizontal('left');
        $sheet->getStyle('A1')->getFont()->setSize(22); //大小
        $sheet->getStyle('A1:O3')->getFont()->setBold(true); //粗体

        /**
         * 设置边框
         */
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' =>  Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $sheet->getStyle('A2:O'.$this->totalRow)->applyFromArray($styleArray);
    }

}
